import React, { Component } from 'react';
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
}

class PicturesWall extends Component {
    state = {
        previewVisible: false,//标识是否预览
        previewImage: '',//大图url
        fileList: [
          {
            uid: '-1', //每个file都有一个唯一的id
            name: 'image.png',
            status: 'done', //图片的状态 done:已上传  uploading:上传中  removed:已删除
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
          }
        ],
      };
      

      /**
       * 隐藏modal
       * @returns 
       */
      handleCancel = () => this.setState({ previewVisible: false });
    
      handlePreview = async file => {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
    
        this.setState({
          previewImage: file.url || file.preview,
          previewVisible: true,
          previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
      };
      

      /**
       * file: 当前操作的图片文件(上传/删除)
       * fileList: 所有已上传图片文件对象的数组
       * @param {*} param0 
       */
      handleChange = ({ file, fileList }) => {
        console.log('fileList:', fileList);
        // 一旦上传成功，将当前上传的file的信息修正(name, url)
        this.setState({ fileList })
      };
    
      render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
          </div>
        );
        return (
          <>
            <Upload
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              accept="image/*"
              listType="picture-card"
              fileList={fileList}
              name="image" //请求参数名
              onPreview={this.handlePreview}
              onChange={this.handleChange}
            >
              {fileList.length >= 8 ? null : uploadButton}
            </Upload>
            <Modal
              visible={previewVisible}
              footer={null}
              onCancel={this.handleCancel}
            >
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </>
        );
    }
}
 
export default PicturesWall;